import axios from 'axios'
import store from '@/store'
// import router from '@/router'
import { Message } from 'element-ui'
// import { removeToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // 定义20秒超时
})

service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { success, message } = response.data
    if (success) return response.data
    else {
      Message.error(message) // 统一提示(必须提示),成功可以在外面自行决定是否提示,成功数据外面也要使用

      return Promise.reject(message)
    }
  },
  error => {
    Message.error(error)
    if (error?.response?.data?.code === 10002) {
      // removeToken()
      // store.commit('user/RESET_STATE')
      // router.replace('/login')
      store.dispatch('user/logoutActions')
    }
    return Promise.reject(error)
  }
)

export default service
